package com.tianzmp.ttq.admin.service.impl;

import cn.hutool.core.io.FileUtil;
import com.tianzmp.ttq.admin.config.SystemConfiguration;
import com.tianzmp.ttq.admin.controller.resDto.FileAddResponse;
import com.tianzmp.ttq.admin.entity.UpsFile;
import com.tianzmp.ttq.admin.mapper.UpsFileMapper;
import com.tianzmp.ttq.admin.service.IUpsFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


/**
 * @author zhumengping
 */
@Service
public class UpsFileServiceImpl implements IUpsFileService {


    @Autowired
    UpsFileMapper dao;

    @Autowired
    private SystemConfiguration systemConfiguration;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public FileAddResponse upload(MultipartFile file){
        FileAddResponse response = new FileAddResponse();
        String originalFilename = file.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String filePath = systemConfiguration.getFilePath();
        String newName = UUID.randomUUID().toString().replace("-", "");
        String suffix = originalFilename.substring(i);
        String initName = originalFilename.substring(0,i);
        String rootPath = filePath + File.separator+ "filePath" +File.separator+ newName+suffix;
        String fileUrl = File.separator + "filePath" +File.separator+ newName+ suffix;
        try {
            FileUtil.writeFromStream(file.getInputStream(),new File(rootPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        UpsFile  upsFile= new UpsFile();
        upsFile.setInitName(initName);
        upsFile.setNewName(newName);
        upsFile.setFileUrl(fileUrl);
        upsFile.setRootPath(rootPath);
        upsFile.setSuffix(suffix);
        dao.insert(upsFile);
        response.setId(upsFile.getId());
        response.setSourceUrl(fileUrl);
        return response;
    }

}
